//
//  ProductDetailVC.swift
//  BaseSwift
//
//  Created by gh on 2019/10/15.
//  Copyright © 2019 ghwang. All rights reserved.
//

import UIKit
import JXPhotoBrowser
import EasyNavigation
import AVKit

class ProductDetailVC: UIViewController {

    var weeks:Array<String> = Array()
    var dates:Array<String> = Array()
    var btns:Array<UIButton> = Array()

    var lastMenuBtn:UIButton?
    
    var product:ProductVo?
    var cellContentV = UIView()
    var DHeight:Float = 0.00
    var headerHeight: Float = 0.00
    
    var navDHeight:CGFloat = 0.00
    var navDHeight3:CGFloat = 0.00
    var navDHeight4:CGFloat = 0.00
    


    var isClick = false

    

    
    var playerCtrl:AVPlayerViewController?



    var commentVo:CommentVo?
    var tripHeight:CGFloat = 0.00
    
    var featureView: UIView?
    var tripView: UIView?
    var costView: UIView?
    var bookView: UIView?
    
    var tempView0: UIView?
    var tempView1: UIView?
    var tempView2: UIView?
    var tempView3: UIView?


    

    lazy var navView:UIView = {
        
        let bg = UIView()
        bg.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: HT_StatusBarAndNavigationBarHeight)
        
        let backBtn = UIButton()
        backBtn.setImage(UIImage(named: "back_white"), for: .normal)
        backBtn.addTarget(self, action: #selector(backClick), for: .touchUpInside)
        bg.addSubview(backBtn)
        let _ = backBtn.sd_layout()?.leftSpaceToView(bg,10)!.heightIs(35)!.topSpaceToView(bg,HT_StatusBarHeight)!.widthIs(35)
        
        let moreBtn = UIButton()
        moreBtn.setImage(UIImage(named: "more_white"), for: .normal)
        moreBtn.addTarget(self, action: #selector(moreBtnClick), for: .touchUpInside)
        bg.addSubview(moreBtn)
        let _ = moreBtn.sd_layout()?.rightSpaceToView(bg,10)!.heightIs(35)!.topSpaceToView(bg,HT_StatusBarHeight)!.widthIs(35)
        
        
        let shareBtn = UIButton()
        shareBtn.setImage(UIImage(named: "share_white"), for: .normal)
        shareBtn.addTarget(self, action: #selector(shareBtnClick), for: .touchUpInside)
        bg.addSubview(shareBtn)
        let _ = shareBtn.sd_layout()?.rightSpaceToView(moreBtn,10)!.heightIs(35)!.topSpaceToView(bg,HT_StatusBarHeight)!.widthIs(35)
        
        
        return bg
        
        
    }()
    
    lazy var HeaderView:UIView = {
        
        let bg = UIView()
        bg.backgroundColor = UIColor.backgroundColor
        bg.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: 210+130+165+10)//去掉了128+10
        

        var imgs = Array<String>()
        var isVideo = false
        var vipath = ""
        for item in self.product!.productPicList!  {
            
            imgs.append(item.url ?? "")
            if item.type == "VIDEO" {
                
                isVideo = true
                vipath = item.url!
            }
        }
        let sdCyc = SDCycleScrollView.init(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 210), imageNamesGroup: imgs)
        sdCyc?.backgroundColor =  UIColor.paddingColor
        sdCyc!.showPageControl = false
        sdCyc!.pageDotColor = UIColor.white
        if isVideo == true{
            
            sdCyc?.placeholderImage = BZHttpFileHelper.firstFrame(withVideoURL: URL(string: vipath)!, size: CGSize(width: KScreenWidth, height: 210))
            let playIcon = UIImageView()
            playIcon.image = UIImage(named: "playvideo")
            sdCyc?.addSubview(playIcon)
            let _ = playIcon.sd_layout()?.widthIs(45)!.heightIs(45)!.centerXEqualToView(sdCyc)!.centerYEqualToView(sdCyc)

        }else{
            
            sdCyc?.placeholderImage = UIImage(named: "holder_big")

        }
        sdCyc?.delegate = self
        bg.addSubview(sdCyc!)
        
        
        let infoView = UIView()
        infoView.backgroundColor = UIColor.white
        bg.addSubview(infoView)
        let nameHei = self.product?.pdtName?.replacingOccurrences(of: "#", with: " ").stringHeightWith(fontSize: 18, width: KScreenWidth-32)

        infoView.frame = CGRect(x: 0, y: 195, width: KScreenWidth, height: 110+nameHei!)
        infoView.SetMutiBorderRoundingCornersTLTR(infoView, corner: 20)
        
        let nameLab = UILabel()
        infoView.addSubview(nameLab)
        nameLab.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight(rawValue: 0.2))
        
        nameLab.textColor = UIColor.textTitleColorBlack
        nameLab.text = self.product?.pdtName?.replacingOccurrences(of: "#", with: " ")
        let _ = nameLab.sd_layout()?.leftSpaceToView(infoView,16)?.autoHeightRatio(0)?.rightSpaceToView(infoView,16)?.topSpaceToView(infoView,16)
        nameLab.setMaxNumberOfLinesToShow(6)
        
        let tags = self.product?.tags?.split(string: ",")
        nameLab.updateLayout()
        let tagsView = STTagsView.tagView(withFrame: CGRect(x: 14, y: nameLab.frame.maxY-5, width: infoView.width-40, height: 15), tagsArray: tags, textColor: UIColor.GP_Blue_Color, textFont: UIFont .systemFont(ofSize: 10), normalTagBackgroundColor: UIColor.backgroundColor, tagBorderColor: UIColor.GP_Blue_Color, contentInsets: UIEdgeInsets(top: 10, left: 5, bottom: 10, right: 5), labelContentInsets: UIEdgeInsets(top: 3, left: 3, bottom: 3, right: 3), labelHorizontalSpacing: 5, labelVerticalSpacing: 5)
        infoView.addSubview(tagsView!)
        
        
        let priceLab = UILabel()
        infoView.addSubview(priceLab)
        priceLab.font = UIFont.titleFont
        priceLab.textColor = UIColor.GP_Orange_Color
        priceLab.text = String(format: "￥%.2f起", self.product!.salePrice!)
        let _ = priceLab.sd_layout()?.leftSpaceToView(infoView,16)?.heightIs(15)?.rightSpaceToView(infoView,16)?.topSpaceToView(nameLab,35)
        
        
        let introLab = UILabel()
        infoView.addSubview(introLab)
        introLab.font = UIFont.smallerFont
        introLab.textColor = UIColor.textPlaceHolderColor
        introLab.text = String(format: "出发地:%@", self.product!.basePlace!)
        let _ = introLab.sd_layout()?.leftSpaceToView(infoView,16)?.heightIs(15)?.rightSpaceToView(infoView,16)?.topSpaceToView(priceLab,16)
        
        let dateView = UIView()
        dateView.isHidden = true
        bg.addSubview(dateView)
        dateView.backgroundColor = UIColor.white
        let _ = dateView.sd_layout()?.widthRatioToView(bg,1)!.heightIs(110)!.topSpaceToView(infoView,10)
        
        let topV0 =  UIView()
        dateView.addSubview(topV0)
        let _ = topV0.sd_layout()?.widthRatioToView(dateView,1)!.heightIs(40)!.topSpaceToView(dateView,0)

        
        if self.product?.productDailyPriceList?.count == 0{
            
            
            
            let labbbb = UILabel()
            dateView.addSubview(labbbb)
            labbbb.font = UIFont.commonFontSmaller
            labbbb.textAlignment = .center
            labbbb.textColor = UIColor.textPlaceHolderColor
            labbbb.text = "暂无价格"
            let _ = labbbb.sd_layout()?.widthIs(115)!.heightIs(28)!.centerXEqualToView(topV0)!.topSpaceToView(topV0,-5)
            
        }else{
            

            
            let tlab0 = UILabel()
            topV0.addSubview(tlab0)
            tlab0.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight(rawValue: 0.2))
            tlab0.textColor = UIColor.textTitleColorBlack
            tlab0.text = "选择类型和日期"
            let _ = tlab0.sd_layout()?.leftSpaceToView(topV0,16)?.heightIs(22)?.rightSpaceToView(topV0,96)?.centerYEqualToView(topV0)
            
            let dateBtn = UIButton()
            dateBtn.addTarget(self, action: #selector(dateBtnClck), for: .touchUpInside)
            dateBtn.setTitle("立即报名> ", for: .normal)
            dateBtn.titleLabel?.font = UIFont.commonFontSmaller
            dateBtn.setTitleColor(UIColor.tabbarDefaultTextColor, for: .normal)
            topV0.addSubview(dateBtn)
            let _ = dateBtn.sd_layout()?.heightIs(30)!.rightSpaceToView(topV0,16)!.centerYEqualToView(topV0)
            dateBtn.setupAutoSize(withHorizontalPadding: 0, buttonHeight: 30)
            
            
            let stock = self.product?.productDailyPriceList?.first
            
            let time = stock?.saleDate!.split(string: "T").first
            let time1 = stock?.saleDate!.split(string: "T")[1].split(string: ".").first
            let time2 = time! + " "+time1!
            
            let day0 = NSDate()
            let day1 = NSDate.init(daysFromNow: 1)
            let day2 = NSDate.init(daysFromNow: 2)
            let day3 = NSDate.init(daysFromNow: 3)
            
            let dateFormatter  = DateFormatter()
            let weekDayArry = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"]
            dateFormatter.shortWeekdaySymbols = weekDayArry
            dateFormatter.dateFormat = "eee"
            self.weeks.append(dateFormatter.string(from: day0 as Date))
            self.weeks.append(dateFormatter.string(from: day1! as Date))
            self.weeks.append(dateFormatter.string(from: day2! as Date))
            self.weeks.append(dateFormatter.string(from: day3! as Date))

            self.dates.append(day0.formattedDate(withFormat: "MM-dd"))
            self.dates.append(day1!.formattedDate(withFormat: "MM-dd"))
            self.dates.append(day2!.formattedDate(withFormat: "MM-dd"))
            self.dates.append(day3!.formattedDate(withFormat: "MM-dd"))
            
            for index in 0 ..< self.dates.count{
                
                let mod = self.product?.productDailyPriceList?.get(at: 0)
                
                let maskBtn = UIButton()
                maskBtn.sd_cornerRadius = 3
                dateView.addSubview(maskBtn)
                maskBtn.layer.borderColor = UIColor.lineColor.cgColor
                maskBtn.layer.borderWidth = 1
                let padding:CGFloat = (KScreenWidth - 4*88)/4
                maskBtn.frame = CGRect(x: padding + CGFloat(index*93), y: 30+13, width: 88, height: 48)
                
                let dateLab = UILabel()
                dateLab.textAlignment = .center
                dateLab.font = UIFont.smallerLessthanFont
                dateLab.textColor =  UIColor.tabbarDefaultTextColor
                dateLab.text = String(format: "%@ %@", self.dates[index],self.weeks[index])
                maskBtn.addSubview(dateLab)
                let _ = dateLab.sd_layout()?.widthIs(80)!.heightIs(15)!.topSpaceToView(maskBtn,10)!.centerXEqualToView(maskBtn)
                
                
                let priceDayLab = UILabel()
                priceDayLab.textAlignment = .center
                priceDayLab.font = UIFont.systemFont(ofSize: 11, weight: UIFont.Weight(rawValue: 0.3))
                priceDayLab.textColor =  UIColor.GP_Orange_Color
                priceDayLab.text = String(format: "￥%.2f起", mod!.adultPrice)
                maskBtn.addSubview(priceDayLab)
                let _ = priceDayLab.sd_layout()?.widthIs(80)!.heightIs(20)!.topSpaceToView(dateLab,2)!.centerXEqualToView(maskBtn)
                
                
                
                
            }
        }
        


        
        if self.commentVo == nil{
            
            bg.frame = CGRect(x: 0, y: 0, width: Int(KScreenWidth), height: 210+110+Int(nameHei!)-8)

            
            return bg
        }
        
        let commentBg = UIView()
        bg.addSubview(commentBg)
        commentBg.backgroundColor  = UIColor.white
        let _ = commentBg.sd_layout()?.widthRatioToView(bg,1)!.topSpaceToView(infoView,10)!.heightIs(175)
        let topV =  UIView()
        commentBg.addSubview(topV)
        let _ = topV.sd_layout()?.widthRatioToView(commentBg,1)!.heightIs(30)!.topSpaceToView(commentBg,10)
        
        let tlab = UILabel()
        topV.addSubview(tlab)
        tlab.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight(rawValue: 0.2))
        tlab.textColor = UIColor.textTitleColorBlack
        tlab.text = "评论"
        let _ = tlab.sd_layout()?.leftSpaceToView(topV,16)?.heightIs(22)?.rightSpaceToView(topV,96)?.centerYEqualToView(topV)
        
        let moreBtn = UIButton()
        moreBtn.addTarget(self, action: #selector(allCommentsClick), for: .touchUpInside)
        moreBtn.setTitle("全部评论> ", for: .normal)
        moreBtn.titleLabel?.font = UIFont.commonFontSmaller
        moreBtn.setTitleColor(UIColor.tabbarDefaultTextColor, for: .normal)
        topV.addSubview(moreBtn)
        let _ = moreBtn.sd_layout()?.heightIs(30)!.rightSpaceToView(topV,16)!.centerYEqualToView(topV)
        moreBtn.setupAutoSize(withHorizontalPadding: 0, buttonHeight: 30)
        
        
        let commentCell = Bundle.main.loadNibNamed("CommentSampleCell", owner: self, options: nil)?.first  as! CommentSampleCell
        commentBg.addSubview(commentCell)
        commentCell.setModel(mod: self.commentVo!)
        let _ = commentCell.sd_layout()?.widthRatioToView(commentBg,1)!.topSpaceToView(commentBg,40)!.heightIs(175-30)
        
        
        
        
        
        return bg
        
    }()
    lazy var bottomView:UIView = {
        
        
        let bigBg = UIView()
        bigBg.backgroundColor = UIColor.white
          
          
          let bg = UIView()
          bg.backgroundColor = UIColor.white
          bigBg.addSubview(bg)
          let _ = bg.sd_layout()?.widthRatioToView(bigBg,1)?.heightIs(64)!.bottomSpaceToView(bigBg,HT_TabbarSafeBottomMargin)

        let topLine = UIView()
        topLine.backgroundColor = UIColor.lineColor
        bg.addSubview(topLine)
        let _ = topLine.sd_layout()?.widthRatioToView(bg,1)?.heightIs(1)!.topSpaceToView(bg,0)
        
        
        let phoneBtn = UIButton()
        phoneBtn.addTarget(self, action: #selector(phoneClick), for: .touchUpInside)
        phoneBtn.setImage(UIImage(named: "电话_线型"), for: .normal)
        phoneBtn.setTitle("电话", for: .normal)
        phoneBtn.titleLabel?.font = UIFont.commonFontSmaller
        phoneBtn.setTitleColor(UIColor.tabbarDefaultTextColor, for: .normal)
        bg.addSubview(phoneBtn)
        let _ = phoneBtn.sd_layout()?.widthIs(50)?.heightIs(55)!.leftSpaceToView(bg,5)?.centerYEqualToView(bg)
        let _ = phoneBtn.imageView?.sd_layout()?.topSpaceToView(phoneBtn,5)!.widthIs(25)!.heightIs(25)?.centerXEqualToView(phoneBtn)
        phoneBtn.titleLabel?.textAlignment = .center
        let _ = phoneBtn.titleLabel?.sd_layout()?.topSpaceToView(phoneBtn.imageView,2)?.centerXEqualToView(phoneBtn)!.heightIs(20)?.widthIs(50)
        
        
        let zxunBtn = UIButton()
        zxunBtn.addTarget(self, action: #selector(zixunClick), for: .touchUpInside)
        zxunBtn.setImage(UIImage(named: "咨询"), for: .normal)
        zxunBtn.setTitle("咨询", for: .normal)
        zxunBtn.titleLabel?.font = UIFont.commonFontSmaller
        zxunBtn.setTitleColor(UIColor.tabbarDefaultTextColor, for: .normal)
        bg.addSubview(zxunBtn)
        let _ = zxunBtn.sd_layout()?.widthIs(50)?.heightIs(55)!.leftSpaceToView(phoneBtn,5)?.centerYEqualToView(bg)
        let _ = zxunBtn.imageView?.sd_layout()?.topSpaceToView(zxunBtn,5)!.widthIs(25)!.heightIs(25)?.centerXEqualToView(zxunBtn)
        zxunBtn.titleLabel?.textAlignment = .center
        let _ = zxunBtn.titleLabel?.sd_layout()?.topSpaceToView(zxunBtn.imageView,2)?.centerXEqualToView(zxunBtn)!.heightIs(20)?.widthIs(50)
        
        
        let favBtn = UIButton()
        favBtn.setImage(UIImage(named: "收藏"), for: .normal)
        favBtn.setImage(UIImage(named: "faved"), for: .highlighted)

        favBtn.setTitle("收藏", for: .normal)
        favBtn.addTarget(self, action: #selector(favClick), for: .touchUpInside)
        favBtn.titleLabel?.font = UIFont.commonFontSmaller
        favBtn.setTitleColor(UIColor.tabbarDefaultTextColor, for: .normal)
        bg.addSubview(favBtn)
        let _ = favBtn.sd_layout()?.widthIs(50)?.heightIs(55)!.leftSpaceToView(zxunBtn,5)?.centerYEqualToView(bg)
        let _ = favBtn.imageView?.sd_layout()?.topSpaceToView(favBtn,5)!.widthIs(25)!.heightIs(25)?.centerXEqualToView(favBtn)
        favBtn.titleLabel?.textAlignment = .center
        let _ = favBtn.titleLabel?.sd_layout()?.topSpaceToView(favBtn.imageView,2)?.centerXEqualToView(favBtn)!.heightIs(20)?.widthIs(50)
        
        
        
        let payBtn = UIButton()
        bg.addSubview(payBtn)
        payBtn.addTarget(self, action: #selector(nowReportClick), for: .touchUpInside)
        payBtn.sd_cornerRadius = LARAGE_BTN_RADIUS
        let _ = payBtn.sd_layout()?.widthIs(200)?.heightIs(LARAGE_BTN_HEIGHT)?.rightSpaceToView(bg,10)?.centerYEqualToView(bg)
        payBtn.gradientBtnMainColor()
        
        let tlab = UILabel()
        tlab.text = "立即报名"
        tlab.font = UIFont.commonFontSmall
        tlab.textColor = UIColor.white
        tlab.textAlignment = .center
        payBtn.addSubview(tlab)
        let _ = tlab.sd_layout()?.spaceToSuperView(UIEdgeInsets.zero)
        
        return bigBg
    }()
    
    lazy var tableView:UITableView = {
        
        
        var tableView = UITableView()
        tableView.dataSource = self
        tableView.delegate = self
        tableView.backgroundColor = UIColor.clear
        tableView.tableFooterView = UIView()
        tableView.separatorColor = UIColor.clear
        tableView.showsVerticalScrollIndicator = false
        tableView.tableHeaderView = self.HeaderView
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellid0")
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellid1")
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellid2")
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellid3")

        return tableView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()



        // Do any additional setup after loading the view.
        self.view.backgroundColor = UIColor.backgroundColor
        self.navigationView.isHidden  = true
        
        self.tempView0 = self.createNativeDetailView(topType: "FEATURES")
        self.tempView1 = self.createNativeTripDayView()
        self.tempView2 = self.createNativeDetailView(topType: "COST")
        self.tempView3 = self.createNativeDetailView(topType: "BOOK")
        
        view.addSubview(self.tableView)
        let _ = self.tableView.sd_layout()?.spaceToSuperView(UIEdgeInsets(top: 0, left: 0, bottom: HT_TabbarSafeBottomMargin+64, right: 0))
        view.addSubview(self.bottomView)
        let _ = self.bottomView.sd_layout()?.widthRatioToView(view,1)!.heightIs(64+HT_TabbarSafeBottomMargin)!.bottomSpaceToView(view,0)
        
        if #available(iOS 11.0, *) {
            self.tableView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false;
        }
        self.HeaderView.updateLayout()
        self.headerHeight = Float(self.HeaderView.height)
        self.tableView.reloadData()
        view.addSubview(self.navView)
        view.bringSubviewToFront(self.navView)
        
        //内存不足会导致cell上view释放,加了它貌似不会释放。但是确实内存严重不足，就会闪退
        objc_setAssociatedObject(self, "", self, .OBJC_ASSOCIATION_RETAIN)
        
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        


        //self.tableView.reloadRows(at: [IndexPath(row: 1, section: 0),IndexPath(row: 2, section: 0),IndexPath(row: 3, section: 0),], with: .none);
        
    }
    
    @objc func allCommentsClick(){
        
        let vc = CommentSampleVC()
        vc.pid = self.product?.id
        vc.type = "product"
        self.present(EasyNavigationController(rootViewController: vc), animated: true) {
            
        }
        
    }
    @objc func dateBtnClck(){
        
        self.nowReportClick()

    }
    
    @objc func favClick(btn:UIButton){
        
          if SPUtil.init().loginStatus == 0 {
              
              APP.backToVC = self
              PUSH(from: self, to: LoginViewController())
              return
          }
          if SPUtil.init().mobile.count == 0 {
              
              APP.backToVC = self
              PUSH(from: self, to: BindPhoneVC())
              return
        
          }

        API.collect(params: ["type":"COL",
                             "colType":"PRODUCT",
                             "mobile":SPUtil.init().mobile!,
                             "pdtId":(self.product?.id!)!]) { (result) in
            
            
                                ToastUtil.show(msg: "收藏成功")
        }

        btn.isSelected.toggle()
    }
    @objc func backClick(){
        
        POP(vc: self)
    }
    @objc func moreBtnClick(btn:UIButton){
        
        var actions: Array<PopoverAction> = [PopoverAction]()
         for item in ["首页","线路","我的","订单"] {
             
             let action = PopoverAction.init(title: item) { (action) in
                 
                 let vo = action?.model as! String
                if vo == "首页"{
                    

                    APP.initMainVC()
                    
                }else if vo == "线路"{
                    
                    PUSH(from: self, to: RouteViewController())

                }else if vo == "我的"{
                    
                    
                    if SPUtil.init().loginStatus == 0 {
                        
                        PUSH(from: self, to: LoginViewController())
                        return
                    }
                    PUSH(from: self, to: MeViewController())
                    
                }else{
                    let vc = OrderViewController()
                    vc.index = 0
                    PUSH(from: self, to: vc)
                    
                    
                }
                 
                 
                 
             }
             action?.model = item
             actions.append(action!)
             
         }
         let popView = PopoverView.init()
         popView.hideAfterTouchOutside = true
         popView.style = .default
         popView.show(to: btn, with: actions)
        
    }
    @objc func shareBtnClick(){

        let img0 = BZHttpFileHelper.imageWithScreenshot()
        let img1 = BZHttpFileHelper.compressImage(img0, toByte: 50*1024)

        let shareItems:Array = [img1 as Any] as [Any]
                let activityViewController:UIActivityViewController = UIActivityViewController(activityItems: shareItems, applicationActivities: nil)
        activityViewController.excludedActivityTypes = [UIActivity.ActivityType.print, UIActivity.ActivityType.postToWeibo, UIActivity.ActivityType.copyToPasteboard, UIActivity.ActivityType.addToReadingList, UIActivity.ActivityType.postToVimeo]
                self.present(activityViewController, animated: true, completion: nil)
    }
    
    @objc func phoneClick(){
        
        ToastUtil.showAlert(context: self, title: "提示", msg: "是否拨打电话\(Constant.PHONE)", sureTitle: "拨打") {
            
            let str = String(format: "tel://%@", Constant.PHONE)
            UIApplication.shared.openURL(URL(string: str)!)
        }
        
    }
    

    var tbg:UIView?

}
extension ProductDetailVC:UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate,SDCycleScrollViewDelegate{
    
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        
        let yOffset: Float = Float(scrollView.contentOffset.y)
        if self.isClick == true{
            
            self.isClick = false
        }
        if yOffset <= 0 {
            
            self.navView.isHidden = false
            self.tableView.sd_y = 0
           
        }

    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        
        let yOffset: Float = Float(scrollView.contentOffset.y)

        if yOffset <= 0 {
            
            self.navView.isHidden = false
            self.tableView.sd_y = 0
           
        }
    }
    
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {

        let yOffset: Float = Float(scrollView.contentOffset.y)+500

        var index = 0
        
        //print("two:\(ori + self.DHeight)")
//        print("three:\(ori+self.DHeight+self.DHeight1 )")
//        print("four:\(ori+self.DHeight+self.DHeight1 + self.DHeight2 )")
        //print("srcTripHeight:\(self.tripHeight)")



        if yOffset > headerHeight + Float(self.navDHeight)  {
            
 
            index = 1
            
        }
        if  yOffset > headerHeight + Float(self.navDHeight)+Float(self.tripHeight){
            

            index = 2

            
        }
        if  yOffset > headerHeight + Float(self.navDHeight)+Float(self.tripHeight)+Float(self.navDHeight3){
            

            index = 3

            
        }

        if self.isClick == true  {
            
            return
        }
        if yOffset > 850{
            
            self.tableView.sd_y = HT_StatusBarHeight

        }
        
        
        if self.btns.count == 4 {
                
            let btn = self.btns[index]
            btn.setTitleColor(UIColor.textTitleColorBlack, for: .normal)
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight(rawValue: 0.2))
            let icon = btn.viewWithTag(8787) as! UIImageView
            icon.isHidden = false
            
            if lastMenuBtn != btn {
                
                self.lastMenuBtn!.setTitleColor(UIColor.tabbarDefaultTextColor, for: .normal)
                self.lastMenuBtn!.titleLabel?.font = UIFont.commonFont
                let icon = lastMenuBtn!.viewWithTag(8787) as! UIImageView
                icon.isHidden = true
            }
            self.lastMenuBtn = btn
            
        }
        
        if yOffset-500 <= 0 {
            
            self.navView.isHidden = false
            self.tableView.sd_y = 0
           
        }

        if yOffset-500 > Float(HT_StatusBarAndNavigationBarHeight){
            
            self.navView.isHidden = true

        }

    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        
        return 4
        
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        if section == 0 {
            
            return 44

        }else{
            
            return 0
        }
    }

    func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        

    }


    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        if tbg != nil{
            
            return tbg
        }
        
        tbg = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 60+HT_StatusBarHeight))
        tbg!.backgroundColor =  UIColor.white
        
        let scrMenuBg = UIScrollView()
        tbg!.addSubview(scrMenuBg)
        scrMenuBg.backgroundColor = UIColor.white
        let  tits = ["产品特色","详情行程","费用说明","预订须知"]
        
        let _ = scrMenuBg.sd_layout()?.widthRatioToView(tbg!,1)!.heightIs(55)!.centerYEqualToView(tbg)
        for index in 0 ..< tits.count{
            
            let menuBtn = UIButton()
            btns.append(menuBtn)
            menuBtn.tag = 9090+index
            menuBtn.addTarget(self, action: #selector(topMenuClick), for: .touchUpInside)
            let width:CGFloat = KScreenWidth/4
            
            menuBtn.frame = CGRect(x: CGFloat(index)*width, y: 5, width: KScreenWidth/4, height: 45)
            menuBtn.setTitle(tits[index], for: .normal)
            menuBtn.titleLabel?.font = UIFont.commonFont
            menuBtn.setTitleColor(UIColor.tabbarDefaultTextColor, for: .normal)
            scrMenuBg.addSubview(menuBtn)
            scrMenuBg.setupAutoContentSize(withRightView: menuBtn, rightMargin: 0)
            scrMenuBg.showsHorizontalScrollIndicator = false
            
            let icon = UIImageView()
            menuBtn.addSubview(icon)
            icon.backgroundColor = UIColor.GP_Orange_Color
            let _ = icon.sd_layout()?.widthRatioToView(menuBtn,1)!.bottomSpaceToView(menuBtn,0)!.heightIs(2)
            icon.tag = 8787
            icon.isHidden = true
            
            if index==0 && self.lastMenuBtn == nil {
                
                icon.isHidden = false
                self.lastMenuBtn = menuBtn
                menuBtn.setTitleColor(UIColor.textTitleColorBlack, for: .normal)
                menuBtn.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight(rawValue: 0.2))


            }
        }
        
        return tbg
    }



    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.row == 0  {
            
            return CGFloat(self.navDHeight+40)
            
        }else if indexPath.row == 1 {
            
            return CGFloat(self.tripHeight)

        }else if indexPath.row == 2 {
            
            return CGFloat(self.navDHeight3 + 40)

        }else if indexPath.row == 3 {
            
            return CGFloat(self.navDHeight4 + 40)

        }else{
            return 0
        }
    }
    

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.row == 0 {
            
              
            let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cellid0")!
               cell.selectionStyle = .none
               cell.backgroundColor = UIColor.white

               if featureView == nil {
                
        
                let titleLab = UILabel()
                titleLab.text = "产品特色"
                titleLab.backgroundColor = UIColor.white
                titleLab.font = UIFont.titleFont
                titleLab.textColor = UIColor.textTitleColorBlack
                titleLab.textAlignment = .center
                
                cell.contentView.addSubview(titleLab)
                let _ = titleLab.sd_layout()?.topSpaceToView(cell.contentView,0)!.heightIs(35)!.widthRatioToView(cell.contentView,1)
                       
                
                self.featureView = self.tempView0
                cell.contentView.addSubview(self.featureView!)
                let _ = self.featureView!.sd_layout()?.widthRatioToView(cell.contentView,1)!.topSpaceToView(cell.contentView,45)!.autoHeightRatio(0)
                //self.tableView.reloadData()

                
                let paddingView = UIView()
                paddingView.backgroundColor = UIColor.lineColor
                cell.contentView.addSubview(paddingView)
                let _ = paddingView.sd_layout()?.widthRatioToView(cell.contentView,1)!.heightIs(10)!.bottomSpaceToView(cell.contentView,0)
                

               }

            return cell
            
        }else if indexPath.row == 1{
            
              let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cellid1")!
               cell.selectionStyle = .none
               cell.backgroundColor = UIColor.white

            
            if self.tripView == nil {
                
     
                
                let titleLab = UILabel()
                titleLab.text = "详细行程"
                titleLab.backgroundColor = UIColor.white
                titleLab.font = UIFont.titleFont
                titleLab.textColor = UIColor.textTitleColorBlack
                titleLab.textAlignment = .center
                
                cell.contentView.addSubview(titleLab)
                let _ = titleLab.sd_layout()?.topSpaceToView(cell.contentView,10)!.heightIs(25)!.widthRatioToView(cell.contentView,1)

                
                self.tripView = self.tempView1
                //self.tripView = self.createNativeTripDayView()
                cell.contentView.addSubview(self.tripView!)
                let _ = self.tripView!.sd_layout()?.widthRatioToView(cell.contentView,1)!.topSpaceToView(cell.contentView,45)!.autoHeightRatio(0)
                //self.tableView.reloadData()
                
                let paddingView = UIView()
                paddingView.backgroundColor = UIColor.lineColor
                cell.contentView.addSubview(paddingView)
                let _ = paddingView.sd_layout()?.widthRatioToView(cell.contentView,1)!.heightIs(10)!.bottomSpaceToView(cell.contentView,0)
                

                       
  

               }

            return cell
            
            
        }else if indexPath.row == 2{
            
                let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cellid2")!
                 cell.selectionStyle = .none
                 cell.backgroundColor = UIColor.white

              
            if self.costView == nil {

                let titleLab = UILabel()
                titleLab.text = "费用说明"
                titleLab.backgroundColor = UIColor.white
                titleLab.font = UIFont.titleFont
                titleLab.textColor = UIColor.textTitleColorBlack
                titleLab.textAlignment = .center
                
                cell.contentView.addSubview(titleLab)
                let _ = titleLab.sd_layout()?.topSpaceToView(cell.contentView,10)!.heightIs(25)!.widthRatioToView(cell.contentView,1)

                self.costView = self.tempView2
                cell.contentView.addSubview(self.costView!)
                let _ = self.costView!.sd_layout()?.widthRatioToView(cell.contentView,1)!.topSpaceToView(cell.contentView,45)!.autoHeightRatio(0)
                //self.tableView.reloadData()
                

                let paddingView = UIView()
                paddingView.backgroundColor = UIColor.lineColor
                cell.contentView.addSubview(paddingView)
                let _ = paddingView.sd_layout()?.widthRatioToView(cell.contentView,1)!.heightIs(10)!.bottomSpaceToView(cell.contentView,0)


                }

              return cell
            
        }else{
            
            let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cellid3")!
             cell.selectionStyle = .none
             cell.backgroundColor = UIColor.white
            
             if bookView == nil {
              
                let titleLab = UILabel()
                titleLab.text = "预订须知"
                titleLab.backgroundColor = UIColor.white
                titleLab.font = UIFont.titleFont
                titleLab.textColor = UIColor.textTitleColorBlack
                titleLab.textAlignment = .center
                
                cell.contentView.addSubview(titleLab)
                let _ = titleLab.sd_layout()?.topSpaceToView(cell.contentView,10)!.heightIs(25)!.widthRatioToView(cell.contentView,1)



                self.bookView = self.tempView3
                cell.contentView.addSubview(self.bookView!)
                let _ = self.bookView!.sd_layout()?.widthRatioToView(cell.contentView,1)!.topSpaceToView(cell.contentView,45)!.autoHeightRatio(0)
                //self.tableView.reloadData()

             }

          return cell
            
        }
        
    }
    
    func cycleScrollView(_ cycleScrollView: SDCycleScrollView!, didSelectItemAt index: Int) {
        
        let mod = self.product?.productPicList?.get(at: index)
        if mod!.url!.hasSuffix("mp4") {
            
            self.playerCtrl = AVPlayerViewController()
            let asset = AVAsset(url: URL(string: mod!.url!)!)
           let pitem = AVPlayerItem(asset: asset)
           self.playerCtrl?.player = AVPlayer(playerItem: pitem)
           self.playerCtrl?.videoGravity = .resizeAspectFill
           self.playerCtrl?.player?.play()
           self.playerCtrl?.showsPlaybackControls = true
           self.playerCtrl?.view.bounds = CGRect(x: 0, y: 0, width: KScreenWidth, height: 210)
           self.view.addSubview(self.playerCtrl!.view)
           self.view.bringSubviewToFront(self.playerCtrl!.view)
           
           self.present(self.playerCtrl!, animated: true) {
               
           }
            
            return
        }
        
        
        var imgs = [String]()
        for item in self.product!.productPicList!{
            
            imgs.append(item.url!)
        }

        
        let datas = JXNetworkingDataSource(photoLoader: JXKingfisherLoader(), numberOfItems: { () -> Int in
            return imgs.count
        }, placeholder: { (num) -> UIImage? in
            
            return nil
            
        }) { (num) -> String? in
            
            return imgs.get(at: num)
        }
        
        JXPhotoBrowser(dataSource: datas).show(pageIndex: index)
    }
    @objc func topMenuClick(btn:UIButton){
        
        self.isClick = true
        self.navView.isHidden = true
        self.tableView.sd_y = HT_StatusBarHeight


        btn.setTitleColor(UIColor.textTitleColorBlack, for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight(rawValue: 0.2))
        let icon = btn.viewWithTag(8787) as! UIImageView
        icon.isHidden = false

        if lastMenuBtn != btn {

            self.lastMenuBtn!.setTitleColor(UIColor.tabbarDefaultTextColor, for: .normal)
            self.lastMenuBtn!.titleLabel?.font = UIFont.commonFont
            let icon = lastMenuBtn!.viewWithTag(8787) as! UIImageView
            icon.isHidden = true
        }
        
        
        self.tableView.scrollToRow(at:IndexPath(row:btn.tag-9090, section:0 ) , at:.top, animated: true)

        self.lastMenuBtn = btn
        
    }
    
       func createHtml(type:String) -> String{
           
           var html = ""
        
        if type == "TRIP" {
            
            for item in self.product!.productTripList! {
                
                let day = String(format: "D%@", item.days.description)
                let place = String(format: "%@  %@~%@", day,item.startPlace!,item.endPlace!)
                let placeNode = String(format: "<h3 style=\"text-align: justify; line-height: 1em;\"><span style=\"color: rgb(0.6, 0.6, 0.6); font-family: 宋体, font-size:18em;SimSun;\">%@</span></h3>",place)
                html += placeNode
                
                let jiaotongNode = String(format: "<p style=\"text-align: justify; line-height: 1em;\"><span style=\"color: rgb(104, 104, 104); font-family: 宋体,SimSun;\">%@</span></p>",item.trafficContext!)
                html += jiaotongNode
                
                let sceNode = String(format: "<p style=\"text-align: justify; line-height: 1em;\"><span style=\"color: rgb(104, 104, 104); font-family: 宋体,SimSun;\">%@</span></p>",item.scenicContext!)
                html += sceNode
                
                let imgs = item.scenicPics?.split(string: ",")
                
                for imgurl in imgs!{
                    
                    let imgNode = String(format: "</p><p style=\"text-align: justify; line-height: 2em;\"><img title=\"\" alt=\"\" src=\"%@\"/></p>", imgurl)
                    
                    html += imgNode
                }


                

                
                let placeNode1 = String(format: "<h4 style=\"text-align: justify; line-height: 1em;\"><span style=\"color: rgb(0.6, 0.6, 0.6); font-family: 宋体, font-size:18em;SimSun;\">%@</span></h4>","餐食")
                html += placeNode1
                
                let foodNode = String(format: "<p style=\"text-align: justify; line-height: 1em;\"><span style=\"color: rgb(104, 104, 104); font-family: 宋体,SimSun;\">%@</span></p>",item.lunch!)
                html += foodNode
                
                
                let placeNode2 = String(format: "<h4 style=\"text-align: justify; line-height: 1em;\"><span style=\"color: rgb(0.6, 0.6, 0.6); font-family: 宋体, font-size:18em;SimSun;\">%@</span></h4>","住宿")
                html += placeNode2
                let liveNode = String(format: "<p style=\"text-align: justify; line-height: 1em;\"><span style=\"color: rgb(104, 104, 104); font-family: 宋体,SimSun;\">%@</span></p>",item.hotel!)
                html += liveNode
                
                
            }
            
            return html
        }
           
           for item in self.product!.productDetailList! {
               
               
               
               if item.type == "text"  && type == item.topCode  {
                   
                   let pNode = String(format: "<p style=\"text-align: justify; font-Size:10px line-height: 2em;\"><span style=\"color: rgb(104, 104, 104); font-family: 宋体, SimSun;\">%@</span></p>", item.conUrl!)
                   html += pNode


               }else if item.type == "img"  && type == item.topCode{
                   

                   let imgNode = String(format: "</p><p style=\"text-align: justify; line-height: 2em;\"><img title=\"\" alt=\"\" src=\"%@\"/></p>", item.conUrl!)
    
                   html += imgNode
                   
               }else if item.type == "video"  && type == item.topCode{
                   
                let videoNode = String(format: "<video controls poster=\"%@\" class=\"edui-upload-video  vjs-default-skin        video-js\" controls=\"\" preload=\"meta\" width=\"100%@\" height=\"280\" src=\"%@\"><source src=\"%@\" type=\"video/mp4\"/></video>", item.conUrl!,"%",item.videoUrl!,item.videoUrl!)
                   html += videoNode

               }

           }
           return html
       }
    
    
    func creatContentView(type:String) -> UIView {
        
        let bg =  UIView()
        bg.backgroundColor = UIColor.white
        
        let containerView = UIView()
        bg.addSubview(containerView)
        containerView.backgroundColor = UIColor.white
        var temp = Array<UIView>()
        
        
        
        for item in self.product!.productDetailList! {
            
            if item.type == "text" && type == item.topCode {
                
                let lab = UILabel()
                lab.text = item.conUrl
                containerView.addSubview(lab)
                let _ = lab.sd_layout()?.autoHeightRatio(0)
                lab.setMaxNumberOfLinesToShow(999)
                temp.append(lab)

            }else if item.type == "img" && type == item.topCode{
                
                let imgv = UIImageView()
                containerView.addSubview(imgv)
                let _ = imgv.sd_layout()?.heightIs(185)
                imgv.sd_setImage(with: URL(string:item.conUrl!), placeholderImage: UIImage(named: "holder"), options: .lowPriority) { (A, B, C, D) in
                    
                }
                temp.append(imgv)
                
            }else if item.type == "video" && type == item.topCode{
                
                let imgv = UIImageView()
                imgv.backgroundColor = UIColor.cccColor
                containerView.addSubview(imgv)
                let _ = imgv.sd_layout()?.heightIs(185)
                
                imgv.sd_setImage(with: URL(string:item.videoUrl!), placeholderImage: UIImage(named: "holder"), options: .lowPriority) { (A, B, C, D) in
                    
                }
                temp.append(imgv)
            }

        }
        let _ = containerView.sd_layout()?.topSpaceToView(bg,0)?.widthRatioToView(bg,1)
        
        containerView.setupAutoWidthFlowItems(temp, withPerRowItemsCount: 1, verticalMargin: 0, horizontalMargin: 0, verticalEdgeInset: 0, horizontalEdgeInset: 0)
        
        
        bg.setupAutoHeight(withBottomView: containerView, bottomMargin: 10)
        bg.updateLayout()
        DHeight = Float(bg.height)
        return bg
    }
    
    
    @objc func nowReportClick(){
        
        
        if self.product?.productProList!.count == 0 {

            ToastUtil.show(msg: "该产品暂没有套餐")
            return
        }
        
        let vc = CalendarViewController()
        vc.product = self.product
        vc.curProduct = self.product?.productProList?.first

                                
        PUSH(from: self, to: vc)
        

        


        
    }

    @objc func zixunClick(){
        
          if SPUtil.init().loginStatus == 0 {
              
              APP.backToVC = self
              PUSH(from: self, to: LoginViewController())
              return
          }
          if SPUtil.init().mobile.count == 0 {
              
              APP.backToVC = self
              PUSH(from: self, to: BindPhoneVC())
              return
        
          }
        
        let vc = ZiXunViewController()
        vc.product = self.product
        PUSH(from: self, to: vc)
    }
    
    func createNativeTripDayView() -> UIView {
        
        
        self.tripHeight = 0
        let bg = UIView()
    
        var temp = Array<UIView>()
        
        for index in 0 ..< self.product!.productTripList!.count{
            
            let item = self.product!.productTripList?.get(at: index)
            let dic = self.createTripCell(mod: item!)
            let cell = dic["view"] as! UIView
            bg.addSubview(cell)
            
            
            
            if  index == self.product!.productTripList!.count-1 {
                
                let  _ = cell.sd_layout()?.heightIs((dic["height"] as! CGFloat)+40)
                self.tripHeight += (dic["height"] as! CGFloat)+40

                
            }else{
                
                let  _ = cell.sd_layout()?.heightIs(dic["height"] as! CGFloat)
                self.tripHeight += dic["height"] as! CGFloat


            }
            

            temp.append(cell)
        }

        bg.setupAutoMarginFlowItems(temp, withPerRowItemsCount: 1, itemWidth: self.view.width, verticalMargin: 0, verticalEdgeInset: 0, horizontalEdgeInset: 0)
        
        return bg
        
    }


    func createTripCell(mod: ProductTripList) -> [String: Any]{

        let path = UIBezierPath()

        var subHeight: CGFloat = 0.00
        
        let bg = UIView()
        
        let dayLab = UILabel()
        bg.addSubview(dayLab)
        dayLab.text = "D"+mod.days
        dayLab.textColor = UIColor.textTitleColorBlack
        dayLab.font = UIFont.systemFont(ofSize: 24, weight: UIFont.Weight(rawValue: 0.3))
        let _ = dayLab.sd_layout()?.leftSpaceToView(bg,16)!.heightIs(24)!.topSpaceToView(bg,0)!.widthIs(45)
        
        let titLab = UILabel()
        bg.addSubview(titLab)
        titLab.text = "\(mod.startPlace! ) -> \(mod.endPlace! )"
        titLab.textColor = UIColor.textTitleColorBlack
        titLab.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight(rawValue: 0.3))
        let _ = titLab.sd_layout()?.leftSpaceToView(bg,60)!.heightIs(22)!.rightSpaceToView(bg,16)!.topSpaceToView(bg,0)
        
        subHeight += 55+24
        

        let icon1 = UIImageView()
        bg.addSubview(icon1)

        let _ = icon1.sd_layout()?.widthIs(24)!.heightIs(24)!.leftSpaceToView(bg,16)!.topSpaceToView(dayLab,23)
        icon1.updateLayout()
        
        let trafficTitleLab = UILabel()
        bg.addSubview(trafficTitleLab)
        trafficTitleLab.textColor = UIColor.textTitleColorBlack
        trafficTitleLab.font = UIFont.commonFontSmaller
        let _ = trafficTitleLab.sd_layout()?.leftEqualToView(titLab)!.heightIs(20)!.topEqualToView(icon1)!.widthIs(35)
        

        
        if mod.traffic == "0" {
            
            icon1.image = UIImage(named: "飞机")
            trafficTitleLab.text = "飞机"

        }else if mod.traffic == "2"{
            
            icon1.image = UIImage(named: "大巴")
            trafficTitleLab.text = "大巴"
            
        }else if mod.traffic == "1"{
            
            icon1.image = UIImage(named: "火车")
            trafficTitleLab.text = "火车"
        }else {
            
            icon1.image = UIImage(named: "邮轮")
            trafficTitleLab.text = "游轮"
        }
        
        let trafficLab = UILabel()
        bg.addSubview(trafficLab)
        
        
        
        trafficLab.text = mod.trafficContext
        
        
        trafficLab.textColor = UIColor.tabbarDefaultTextColor
        trafficLab.font = UIFont.commonFontSmaller
        let myh = mod.trafficContext?.stringHeightWith(fontSize: 14, width: KScreenWidth-60-16)
        let _ = trafficLab.sd_layout()?.leftEqualToView(titLab)!.autoHeightRatio(0)!.topSpaceToView(trafficTitleLab,2)!.rightSpaceToView(bg,16)
        trafficLab.setMaxNumberOfLinesToShow(999)
        
        subHeight = subHeight + 23+24+CGFloat(myh!)
        
        
        
        path.move(to: icon1.layer.position)

        
  
        
        let icon2 = UIImageView()
        bg.addSubview(icon2)
        icon2.image = UIImage(named: "景点01")
        let _ = icon2.sd_layout()?.widthIs(24)!.heightIs(24)!.leftSpaceToView(bg,16)!.topSpaceToView(trafficLab,20)
        icon2.updateLayout()
        
        let parkintroLab = UILabel()
        bg.addSubview(parkintroLab)
        parkintroLab.text = mod.scenic
        parkintroLab.textColor = UIColor.textTitleColorBlack
        parkintroLab.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight(rawValue: 0.3))
        let _ = parkintroLab.sd_layout()?.leftEqualToView(titLab)!.autoHeightRatio(0)!.topEqualToView(icon2)!.rightSpaceToView(bg,16)
        parkintroLab.setMaxNumberOfLinesToShow(999)
        let myh1 = mod.scenic?.stringHeightWith(fontSize: 14, width: KScreenWidth-60-16)

        
        subHeight = subHeight+20+24+CGFloat(myh1!)

        
        path.addLine(to: icon2.layer.position)
        
        var bgscr:UIScrollView?
        if mod.scenicPics!.count > 0 {
            
            var pics = ""
            if (mod.scenicPics! as NSString).hasSuffix(",") {
                
                pics = (mod.scenicPics?.subString(start: 0, length: mod.scenicPics!.count-1))!
                
            }else{
                
                pics = mod.scenicPics!
            }
            
            bgscr = UIScrollView()
            bgscr?.isPagingEnabled = true
            bgscr?.showsHorizontalScrollIndicator = false
            bg.addSubview(bgscr!)
            let _ = bgscr!.sd_layout()?.leftEqualToView(titLab)!.rightSpaceToView(bg,16)!.topSpaceToView(parkintroLab,2)!.heightIs(165)
            
            
            for index in 0 ..< pics.split(string: ",").count{
                
                let url = pics.split(string: ",")[index]

                let imgViewBtn = MyBtn()
                imgViewBtn.tag = 9090+index
                imgViewBtn.frame = CGRect(x: index*Int((KScreenWidth-90)), y: 0, width: Int(KScreenWidth-100), height: 165)

                imgViewBtn.mod = mod
                imgViewBtn.addTarget(self, action: #selector(myBtnClick), for: .touchUpInside)
                bgscr!.addSubview(imgViewBtn)
                bgscr!.setupAutoContentSize(withRightView: imgViewBtn, rightMargin: 0)
                
                imgViewBtn.sd_setImage(with: URL(string: url), for: .normal, placeholderImage: UIImage(named: "holder_big"), options: .allowInvalidSSLCertificates, completed: { (a, b, c, d) in
                    
                })
                
            }

            

            subHeight += 165+2

            
        }
        
        let intro2Lab = UILabel()
        bg.addSubview(intro2Lab)
        
        //景点详情介绍
        intro2Lab.font = UIFont.commonFontSmaller
        intro2Lab.text = mod.scenicContext
        intro2Lab.textColor = UIColor.tabbarDefaultTextColor
        if bgscr != nil {
            
            let _ = intro2Lab.sd_layout()?.leftEqualToView(titLab)!.autoHeightRatio(0)!.topSpaceToView(bgscr,2)!.rightSpaceToView(bg,16)

        }else{
            
            let _ = intro2Lab.sd_layout()?.leftEqualToView(titLab)!.autoHeightRatio(0)!.topSpaceToView(parkintroLab,2)!.rightSpaceToView(bg,16)

        }
        let myh2 = mod.scenicContext?.stringHeightWith(fontSize: 14, width: KScreenWidth-60-16)
        mod.realSceHeight = myh2!
        

        ////折叠button
        let openBtn = MyBtn()
        bg.addSubview(openBtn)

        openBtn.mod = mod
        openBtn.addTarget(self, action: #selector(openCloseBtnClick), for: .touchUpInside)
        if mod.isOpen == true {
            
            intro2Lab.setMaxNumberOfLinesToShow(999)
            subHeight +=  mod.realSceHeight

            openBtn.setImage(UIImage(named: "arrowtop"), for: .normal)


        }else{
            
            intro2Lab.setMaxNumberOfLinesToShow(3)
            subHeight +=  mod.oriSceHeight

            openBtn.setImage(UIImage(named: "arrowdown"), for: .normal)


        }
        
        openBtn.sd_layout()?.rightTo(bg, 12).width(is: 40).height(is:25).topTo(intro2Lab, 0)

        if myh2! < 65 {
            
            openBtn.isHidden = true
            
        }
        
        let icon3 = UIImageView()
          bg.addSubview(icon3)
          icon3.image = UIImage(named: "餐食")
          let _ = icon3.sd_layout()?.widthIs(24)!.heightIs(24)!.leftSpaceToView(bg,16)!.topSpaceToView(intro2Lab,23)
          icon3.updateLayout()
          
          let foodTitleLab = UILabel()
          bg.addSubview(foodTitleLab)
          foodTitleLab.text = "餐食"
          foodTitleLab.textColor = UIColor.textTitleColorBlack
          foodTitleLab.font = UIFont.commonFontSmaller
          let _ = foodTitleLab.sd_layout()?.leftEqualToView(titLab)!.heightIs(20)!.topEqualToView(icon3)!.widthIs(35)
        
        subHeight += 23+24
          
          
          let foodLab = UILabel()
          bg.addSubview(foodLab)
          foodLab.text = mod.lunch
          foodLab.textColor = UIColor.tabbarDefaultTextColor
          foodLab.font = UIFont.commonFontSmaller
          let _ = foodLab.sd_layout()?.leftEqualToView(titLab)!.autoHeightRatio(0)!.topSpaceToView(foodTitleLab,2)!.rightSpaceToView(bg,16)
          foodLab.setMaxNumberOfLinesToShow(999)
        
        let myh3 = mod.lunch?.stringHeightWith(fontSize: 14, width: KScreenWidth-60-16)

        subHeight += CGFloat(myh3!)

        icon3.updateLayout()
        
        path.addLine(to: icon3.layer.position)

        
        let icon4 = UIImageView()
          bg.addSubview(icon4)
          icon4.image = UIImage(named: "住宿")
          let _ = icon4.sd_layout()?.widthIs(24)!.heightIs(24)!.leftSpaceToView(bg,16)!.topSpaceToView(foodLab,23)
          icon4.updateLayout()
          
          let liveTitleLab = UILabel()
          bg.addSubview(liveTitleLab)
          liveTitleLab.text = "住宿"
          liveTitleLab.textColor = UIColor.textTitleColorBlack
          liveTitleLab.font = UIFont.commonFontSmaller
          let _ = liveTitleLab.sd_layout()?.leftEqualToView(titLab)!.heightIs(20)!.topEqualToView(icon4)!.widthIs(35)
          
        subHeight += 23+24

          
          let liveLab = UILabel()
          bg.addSubview(liveLab)
          liveLab.text = mod.hotel
          liveLab.textColor = UIColor.tabbarDefaultTextColor
          liveLab.font = UIFont.commonFontSmaller
          let _ = liveLab.sd_layout()?.leftEqualToView(titLab)!.autoHeightRatio(0)!.topSpaceToView(liveTitleLab,2)!.rightSpaceToView(bg,16)
          liveLab.setMaxNumberOfLinesToShow(999)
        
        var myh4 = mod.hotel?.stringHeightWith(fontSize: 14, width: KScreenWidth-60-16)
        if myh4 == nil {
            
            myh4 = 0
        }

         subHeight += CGFloat(myh4!)
        icon4.updateLayout()

        path.addLine(to: icon4.layer.position)
        path.close()
        
        
        let bline = UIView()
        bline.backgroundColor = UIColor.lineColor
        bg.addSubview(bline)
        bline.frame = CGRect(x: CGFloat(icon1.center.x), y: CGFloat(icon1.center.y), width: 0.5, height: subHeight-180)
        bg.sendSubviewToBack(bline)
        bg.clipsToBounds  =  true
        return ["view":bg,"height":subHeight-60]
        
    }
    
    func createNativeDetailView(topType: String)  -> UIView{
        
        let bg = UIView()
        bg.backgroundColor = UIColor.white
        var temp = Array<UIView>()
        
        
        for item in self.product!.productDetailList! {
            
            if topType == "FEATURES" && topType == item.topCode  {
                
                let dic = self.createProductDetailCell(type: item.type!,mod:item)
                let cell = dic["view"] as! UIView
                bg.addSubview(cell)

                let  _ = cell.sd_layout()?.heightIs(dic["height"] as! CGFloat)
                
                
                self.navDHeight += dic["height"] as! CGFloat
                temp.append(cell)
                

            }else if topType == "COST" && topType == item.topCode  {
                
                
                let dic = self.createProductDetailCell(type: item.type!, mod:item)
                let cell = dic["view"] as! UIView
                bg.addSubview(cell)

                let  _ = cell.sd_layout()?.heightIs(dic["height"] as! CGFloat)
                
                
                self.navDHeight3 += dic["height"] as! CGFloat
                temp.append(cell)


            }else if topType == "BOOK" && topType == item.topCode  {
                
                let dic = self.createProductDetailCell(type: item.type!, mod:item)
                let cell = dic["view"] as! UIView
                bg.addSubview(cell)
                
                let  _ = cell.sd_layout()?.heightIs(dic["height"] as! CGFloat)
                self.navDHeight4 += dic["height"] as! CGFloat
                temp.append(cell)
                
            }

        }
          bg.setupAutoMarginFlowItems(temp, withPerRowItemsCount: 1, itemWidth: self.view.width, verticalMargin: 0, verticalEdgeInset: 0, horizontalEdgeInset: 0)

          return bg
        
    }
    
    func createProductDetailCell(type: String,mod:ProductDetailList) -> [String: Any] {
        
        let bg = UIView()
        var height: CGFloat = 35
        
        if type == "text" {
            
          let lab = UILabel()
          bg.addSubview(lab)
            
            
            
        let paraph0 = NSMutableParagraphStyle()
        //将行间距设置为28
        paraph0.lineSpacing = 10
        //样式属性集合
        let attributes0 = [NSAttributedString.Key.font:UIFont.systemFont(ofSize: 14),
                          NSAttributedString.Key.paragraphStyle: paraph0]
        //lab.attributedText = NSAttributedString(string: mod.conUrl!, attributes: attributes0)
        lab.text = mod.conUrl
        lab.font = UIFont.commonFontSmaller
            
          lab.textColor = UIColor.tabbarDefaultTextColor
          let _ = lab.sd_layout()?.leftSpaceToView(bg,16)!.autoHeightRatio(0)!.topSpaceToView(bg,5)!.rightSpaceToView(bg,16)
          lab.setMaxNumberOfLinesToShow(999)
        
          let labhei = mod.conUrl?.stringHeightWith(fontSize: 14, width: KScreenWidth-32)
            //let labhei = BZHttpFileHelper.getSpaceLabelHeight(mod.conUrl!, with: UIFont.commonFontSmaller, withWidth: KScreenWidth-32)

            height += CGFloat(labhei!)+35
            
            
        }else if type == "img"{
            
            let imgView = MyBtn()
            imgView.addTarget(self, action: #selector(featuLookBigClick), for: .touchUpInside)
            imgView.imgurl = mod.conUrl
            bg.addSubview(imgView)
            imgView.backgroundColor = UIColor.cccColor
            let _ = imgView.sd_layout()?.leftSpaceToView(bg,16)!.heightIs(185)!.topSpaceToView(bg,3)!.rightSpaceToView(bg,16)
            height += 185+6

            imgView.sd_setImage(with: URL(string: mod.conUrl!), for: .normal, placeholderImage: UIImage(named: "holder_big"), options: .allowInvalidSSLCertificates, completed: { (a, b, c, d) in
                
            })

            
            
        }else if type == "video"{
            
            let palyBg = MyBtn()
            palyBg.addTarget(self, action: #selector(feaPlayClick), for: .touchUpInside)
            palyBg.dmod = mod
            bg.addSubview(palyBg)
            let img = BZHttpFileHelper.firstFrame(withVideoURL: URL(string: mod.videoUrl!)!, size:CGSize(width: KScreenWidth, height: 165))
            palyBg.setBackgroundImage(img, for: .normal)
            let _ = palyBg.sd_layout()?.leftSpaceToView(bg,16)!.heightIs(185)!.topSpaceToView(bg,3)!.rightSpaceToView(bg,16)
            height += 185+6
            
            let icon = UIImageView()
            icon.image = UIImage(named: "playvideo")
            palyBg.addSubview(icon)
            let _ =  icon.sd_layout()?.widthIs(45)!.heightIs(45)!.centerXEqualToView(palyBg)!.centerYEqualToView(palyBg)
            
            
            
        }
        
        return ["view":bg,"height":height]
    }
    
    @objc func openCloseBtnClick(btn: MyBtn){
        let mod = btn.mod!
        if  mod.isOpen == true{
            btn.setImage(UIImage(named: "arrowdown"), for: .normal)
            mod.isOpen = false
            
        }else{
            
            btn.setImage(UIImage(named: "arrowtop"), for: .normal)
            mod.isOpen = true
        }
        
        self.tripView?.removeFromSuperview()
        self.tripView = nil
        self.tempView1 = self.createNativeTripDayView()
        tableView.reloadData()
        
    }
    
    @objc func featuLookBigClick(btn: MyBtn){
        
        var imgs = [String]()
        imgs.append(btn.imgurl!)
        let datas = JXNetworkingDataSource(photoLoader: JXKingfisherLoader(), numberOfItems: { () -> Int in
            return imgs.count
        }, placeholder: { (num) -> UIImage? in
            
            return nil
            
        }) { (num) -> String? in
            
            return imgs.get(at: num)
        }
        
        JXPhotoBrowser(dataSource: datas).show(pageIndex: 0)
        
    }
    @objc func feaPlayClick(btn: MyBtn){
        
        let mod = btn.dmod
        self.playerCtrl = AVPlayerViewController()
        let asset = AVAsset(url: URL(string: (mod?.videoUrl!)!)!)
        let pitem = AVPlayerItem(asset: asset)
        self.playerCtrl?.player = AVPlayer(playerItem: pitem)
        self.playerCtrl?.videoGravity = .resizeAspectFill
        self.playerCtrl?.player?.play()
        self.playerCtrl?.showsPlaybackControls = true
        self.playerCtrl?.view.bounds = CGRect(x: 0, y: 0, width: KScreenWidth, height: 210)
        self.view.addSubview(self.playerCtrl!.view)
        self.view.bringSubviewToFront(self.playerCtrl!.view)
        
        self.present(self.playerCtrl!, animated: true) {
            
        }
        
    }
    @objc func myBtnClick(btn: MyBtn){
        
        let mod = btn.mod!
        var imgs = [String]()
        var pics = ""
        if (mod.scenicPics! as NSString).hasSuffix(",") {
            
            pics = (mod.scenicPics?.subString(start: 0, length: mod.scenicPics!.count-1))!
            
        }else{
            
            pics = mod.scenicPics!
        }
        for item in pics.split(string: ","){
            
            imgs.append(item)
        }

        
        let datas = JXNetworkingDataSource(photoLoader: JXKingfisherLoader(), numberOfItems: { () -> Int in
            return imgs.count
        }, placeholder: { (num) -> UIImage? in
            
            return nil
            
        }) { (num) -> String? in
            
            return imgs.get(at: num)
        }

        JXPhotoBrowser(dataSource: datas).show(pageIndex: btn.tag-9090)
        
    }
    
}

class MyBtn: UIButton{
    
    var mod: ProductTripList?
    var dmod: ProductDetailList?
    var imgurl:String?

}
